import { ACTION_TYPE, IAction, IState, ITodo } from "./data"
import Item from "./item"

export const todoListReducer = (state: IState, action: IAction): IState => {
  const { type, payload } = action
  switch (type) {
    case ACTION_TYPE.ADD_TODO:
      return {
        ...state,
        todoList: [payload as ITodo, ...state.todoList]
      }
    case ACTION_TYPE.REMOVE_TODO:
      return {
        ...state,
        todoList: [...state.todoList.filter(item => item.id !== payload)]
      }
    case ACTION_TYPE.TOGGLE_TODO:
      state.todoList.forEach(item => {
        if (item.id === payload) {
          item.completed = !item.completed
        }
      })
      return {
        ...state,
        todoList: [
          ...state.todoList
        ]
      }
    default:
      return state
  }
}
